package shixun;

import java.util.*;

public class Formula {
    private int num1;
    private int num2;
    private String symbol;

    public Formula(int num1, String symbol, int num2) {
        this.num1 = num1;
        this.symbol = symbol;
        this.num2 = num2;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Formula formula = (Formula) o;
        return num1 == formula.num1 && num2 == formula.num2 && symbol.equals(formula.symbol);
    }

    @Override
    public int hashCode() {
        return Objects.hash(num1, num2, symbol);
    }

    @Override
    public String toString() {
        return num1 + " " + symbol + " " + num2;
    }

    public int getAnswer() {
        return symbol.equals("+") ? num1 + num2 : num1 - num2;
    }

    public String toStringAnswer() {
        return num1 + " " + symbol + " " + num2 + " = " + getAnswer();
    }
}
class MathExercises {
    private Set<Formula> formulas;
    private Random random;
    public MathExercises() {
        this.formulas = new LinkedHashSet<>();
        this.random = new Random();
    }
    public void addQuestion(String symbol) {
        while (true) {
            int num1 = random.nextInt(101);
            int num2 = random.nextInt(101-num1);
            if (symbol.equals("+") || (num1 > num2 && symbol.equals("-"))) {
                Formula formula = new Formula(num1, symbol, num2);
                if (formulas.add(formula)) {
                    return;
                }
            }
        }
    }
    public void getSymbol(int count) {
        for (int i = 0; i < count; i++) {
            String symbol = (i % 2 == 0) ? "+" : "-";
            addQuestion(symbol);
        }
    }
    public List<String> getAnswers() {
        List<String> exercises = new ArrayList<>(formulas.size());
        for (Formula f : formulas) {
            exercises.add(f.toStringAnswer());
        }
        return exercises;
    }
    public static void main(String[] args) {
        int[] testCounts = {5, 6, 7, 23, 24, 25, 59, 60, 61, 119, 120};
        MathExercises exercises = new MathExercises();
        System.out.println("题目库:");
        for (int count : testCounts) {
            exercises.formulas.clear();
            exercises.getSymbol(count);
            List<String> questions = exercises.getAnswers();
            System.out.println("测试样例"+count);
            for (int i = 0; i < questions.size(); i++) {
                System.out.printf("%-20s", questions.get(i));
                if ((i + 1) % 6 == 0) {
                    System.out.println();
                }
            }
            System.out.println();
        }
    }
}
